const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')
const { User } = require('../../models/user')
class Auth {
  constructor(whiteList) {
    this.whiteList = whiteList
  }
  get m() {
    return async (ctx, next,) => {
      if (this.whiteList) {
        await next()
        return
      }
      const userToken = basicAuth(ctx.req) //验证token

      let reeMsg = 'token不合法'

      if (!userToken || !userToken.name) {
        throw new global.errs.AuthFailed(reeMsg)
      }
      try {
        // 验证通过 可以拿去 传入的值
        var decode = jwt.verify(userToken.name, global.config.jsonwebtoken.key)

      } catch (error) {
        if (error.name == 'TokenExpiredError') {
          reeMsg = 'token已过期'
        }
        throw new global.errs.AuthFailed(reeMsg)
      }
      // 防止用户被删除,从数据库查询一次
      const res = await User.getUserByUserUserId(decode.uid)
      if (res) {
        ctx.auth = {
          id: decode.uid,
          scope: decode.scope,
        }
      } else {
        throw new global.errs.AuthFailed('token已过期')
      }

      await next()
    }
  }
}
module.exports = { Auth }
